//
//  String+To.swift
//  TTCOM
//
//  Created by Toj on 12/30/22.
//

import Foundation

/** 转对应的类型 */
public extension String {
    
    func to_class<T: NSObject>(T: T.Type) -> T? {
        guard let _ = NSClassFromString(self) else { return nil }
        // 初始化类相当于oc 从 metaclass -> class
        let object = T.init()
        return object
    }
    
    /**
     * 中文 转 unicode
     */
    var to_unicode: String {
        return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? self
    }
    
    /** 转本地图片 */
    var img_named: UIImage? {
        return UIImage(named: self)
    }
    
    var to_image: UIImage? {
        return UIImage(named: self)
    }
    
    var img_resource: UIImage? {
        return UIImage(resource: self)
    }
    
    var to_color: UIColor {
        if isEmpty { return .black }
        return UIColor(hex: self)
    }
    
    var to_cocoaString: NSString {
        return NSString(string: self)
    }
    
    var to_class: AnyClass? {
        guard let cls = NSClassFromString(self) else { return nil }
        return cls
    }
    
    func to_cornerImage(draw bounds: CGRect, radius: CGFloat) -> UIImage? {
        guard !isEmpty else { return nil }
        
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0)
        let path = UIBezierPath(roundedRect: bounds, cornerRadius: radius)
        path.addClip()
        let img = UIImage(named: self)
        img?.draw(in: bounds)
        let cimage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return cimage
    }
}

public extension NSString {
    
    var to_string: String {
        return String(self)
    }
}

/** 编码 */
public extension String {
    
    var to_utf8: Data? {
        return data(using: .utf8)
    }
    
    /**
     ASCII char类型转 Int8
     */
    var to_ASCII: UInt8? {
        if isEmpty { return nil }
        let characters = Array(self)
        return characters.first?.asciiValue
    }
    
    // 字符 编码
    var to_encoded: String {
        let encodeString = addingPercentEncoding(withAllowedCharacters:
                                                            .urlQueryAllowed)
        return encodeString ?? ""
    }
    
    // 转码
    var to_decoded: String {
        return removingPercentEncoding ?? ""
    }
}
